package cn.com.zpark.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @PackageName: cn.com.zpark.filter
 * @ClassName: FilterDemo03
 * @Description:
 * @author: RZS
 * @date: 2021/11/21  15:55
 */
@WebFilter("/filter/*")
public class FilterDemo03 implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("FilterDemo03");
        // 将请求与响应对象强转为HttpServletRequest，HttpServletResponse
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 获取session对象
        HttpSession session = request.getSession();
        // 获取绑定数据
        String user = (String)session.getAttribute("user");

        // 判断用户是否登录
        if(user != null){
            // 登录过滤，放行，继续访问资源
            filterChain.doFilter(request, response);
        }else{
            // 重定向到登录页面
            response.sendRedirect(request.getServletContext().getContextPath()+"/login.html");
        }


    }
}
